
#  generator 类似于 java 的迭代器

def fib1(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b     # generator中每次next迭代，到这里停止，并返回当前b的数值
        a, b = b, a + b
        n = n + 1
    return 'done'

def fib2(max):
    n, a, b = 0, 0, 1
    while n < max:
        # yield b
        a, b = b, a + b
        n = n + 1
    return b

def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)

if __name__ == '__main__':
    f1=fib1(4);
    print(f1);

    f2=fib2(4);
    print(f2);

    print(next(f1));
    print(next(f1));
    print(next(f1));
    print(next(f1));

    o1=odd()
    print(next(o1))
    print(next(o1))

    g=fib1(8)
    while True:
        try:
            value=next(g)
            print("g:",value)
        except StopIteration as e:
            print("Exception'value:",e.value)
            break



